package com.lpinfo.spb.config.webmvc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author kingk
 */
@Configuration
public class LpinfoSpbMvcConfig implements WebMvcConfigurer {

    /**
     * //TODO The first kind of solution by js Precision loss
     * <p>convert field Type is Long  and out of scope in javascript</p>
     * //TODO The second kind of solution by js Precision loss
     * <p> @JsonSerialize(using= ToStringSerializer.class) </p>
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);
    }

    /**
     * kingk
     * global cors config
     * prohibit ALl cors must appoint a unique domain name and rest namespace
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //FIXME 1.禁止全局跨域和全路径跨域
        //FIXME 2.跨域白名单配置
        registry.addMapping("/**")
//                .allowedOrigins("http://192.168.89.89:8081")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .maxAge(3600);
    }



}
